package com.kusej.idno.generation.utils;

import com.google.common.collect.Maps;
import org.apache.commons.io.IOUtils;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;

public class SerializationUtils {
    public static void toFile(Object obj){
        // 将对象序列化到文件
        try {
            FileOutputStream fileOut = new FileOutputStream(obj.getClass().getSimpleName()+".ser");
            ObjectOutputStream out = new ObjectOutputStream(fileOut);
            out.writeObject(obj);
            out.close();
            fileOut.close();
            System.out.println("对象已序列化到文件.ser");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static <T> T toObj(Class<T> clazz){
        // 从文件中反序列化对象
        T obj = null;
        try {
            ObjectInputStream in = new ObjectInputStream(SerializationUtils.class.getClassLoader().getResourceAsStream(clazz.getSimpleName()+".ser"));
            obj = (T) in.readObject();
            in.close();
            System.out.println("从文件.ser中反序列化对象");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return obj;
    }



    public static Map<String, String> readRegionAll(){
        // 从文件中反序列化对象
        ConcurrentMap<String, String> result = Maps.newConcurrentMap();
        try {
            InputStream inputStream = SerializationUtils.class.getClassLoader().getResourceAsStream("regionAll.txt");
            assert inputStream != null;
            String content = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
            String[] split = content.split("\n");
            for (String str:split
                 ) {
                result.put(str.substring(0,6),str.substring(6));
            }
            inputStream.close();
            System.out.println("从文件txt读取");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
